# -*- coding: utf-8 -*-
'''
Copyright 2012 Rich Hill

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
'''



import ReadDatabase
import tweepy
import time
import sys
import os

showdebugmessages=False

def we_are_frozen():
	"""Returns whether we are frozen via py2exe.
	This will affect how we find out where we are located."""
	return hasattr(sys, "frozen")


def module_path():
	""" This will get us the program's directory,
	even if we are frozen using py2exe"""

	if we_are_frozen():
		return os.path.dirname(unicode(sys.executable, sys.getfilesystemencoding( )))

	return os.path.dirname(unicode(__file__, sys.getfilesystemencoding( )))

cwd=module_path()
if cwd=='':
	cwd=os.getcwd()
logfile='%s\\..\\tmp\\log.txt' % cwd	

def debug(message):
	if showdebugmessages:
		log=open(logfile,'a+')
		#outputfile.write('%s,%s\n' % (time.time(), message) )
		try:
			log.write('%s,%s \r\n' %  (time.ctime(),str(message) ))
		except:
			log.write('%s, unable to write message to log' % time.ctime() )
		log.flush()
		log.close()

class Tweet():
	tweettype=''
	tweettext=''
	#tweetvariables={}
	def __init__(self,variables):

		self.variables=variables
		
	def BuildTweet(self):
	
		#print "Building tweet"
		if self.tweettype=="scheduled":
			self.tweettext=u'Scheduled Update:\nForecast = %s\n' % self.variables['currentforecast']
			# we need to put something here that deals with adding sunrise/sunset times
			# the rules:
			# If the first tweet of the day is before sunrise then add todays sunrise time otherwise show todays sunset time
			# if the last tweet of the day is before sunset the add todays sunset time otherwise show tomorrows sunrise time
			current_hour=int(time.gmtime()[3])
			current_min=int(time.gmtime()[4])
			current_sec=int(time.gmtime()[5])
			
			today_sunrise_hour=int(str(self.variables['sunrises'][0]).split(' ')[1].split(':')[0])+time.localtime()[8]
			today_sunrise_min=int(str(self.variables['sunrises'][0]).split(' ')[1].split(':')[1])
			
			today_sunset_hour=int(str(self.variables['sunsets'][0]).split(' ')[1].split(':')[0])+time.localtime()[8]
			today_sunset_min=int(str(self.variables['sunsets'][0]).split(' ')[1].split(':')[1])
			
			tomorrow_sunrise_hour=int(str(self.variables['sunrises'][1]).split(' ')[1].split(':')[0])+time.localtime()[8]
			tomorrow_sunrise_min=int(str(self.variables['sunrises'][1]).split(' ')[1].split(':')[1])
			
			tomorrow_sunset_hour=int(str(self.variables['sunsets'][1]).split(' ')[1].split(':')[0])+time.localtime()[8]
			tomorrow_sunset_min=int(str(self.variables['sunsets'][1]).split(' ')[1].split(':')[1])
			
			if self.variables['scheduleindex']==0:
				# This is the first tweet of the day
				if current_hour <= today_sunrise_hour:
					if current_min <= today_sunrise_min:
						# If now is prior to sun rise add sunrise and sunset time to the tweet
						self.tweettext='%sTodays sunrise = %02d:%02d\n' % (self.tweettext,today_sunrise_hour,today_sunrise_min)
						self.tweettext='%sTodays sunset = %02d:%02d\n' % (self.tweettext,today_sunset_hour,today_sunset_min)
				if current_hour >= today_sunrise_hour:
					if current_min >= today_sunrise_min:
						# now must be after sun rise, so show sunset on tweet
						self.tweettext='%sTodays sunset = %02d:%02d\n' % (self.tweettext,today_sunset_hour,today_sunset_min)
				
				
			if self.variables['scheduleindex']==1:
				# This is the last tweet of the day
				debug( "ch:%s" % str(current_hour) )
				debug( "tssh:%s" % str(today_sunset_hour ) )
				if int(current_hour) >= int(today_sunset_hour):
					#if current_min >= today_sunset_min: #remmed out so that the last tweet of the day sends tomorrows sunrise as long as the hour val > sunset hour
						# If now is after sun set add tomorrows sunrise time to the tweet
						self.tweettext='%sTomorrows sunrise = %02d:%02d\n' % (self.tweettext,tomorrow_sunrise_hour,tomorrow_sunrise_min)
				if current_hour <= today_sunset_hour:
					#if current_min <= today_sunset_min: # remmed out for similar reasons to above
						# now must be before sun set, so show todays sunset and tomorrow sunrise on tweet
						self.tweettext='%sTodays sunset = %02d:%02d\n' % (self.tweettext,today_sunset_hour,today_sunset_min)
						self.tweettext='%sTomorrows sunrise = %02d:%02d\n' % (self.tweettext,tomorrow_sunrise_hour,tomorrow_sunrise_min)
			
		if self.tweettype=="unscheduled":
			self.tweettext=u"Forecast has changed from %s to %s\n" \
				% (self.variables['penultimateforecast'],self.variables['currentforecast'])
			
		self.currenttempsens1=self.variables['lastrecord']['CHN%s_DEG' % self.variables['TweetSensor']]
		self.currenthmdtysens1=self.variables['lastrecord']['CHN%s_RF' % self.variables['TweetSensor']]
		degreesign=u"\N{DEGREE SIGN}"
		#degreesign=""
		
		if self.currenttempsens1 != 0 and self.currenthmdtysens1 !=0 : 
			self.tweettext=u"%sTemperature = %.1f%sC\nHumidity = %d%%\n" \
			% (self.tweettext,self.currenttempsens1,degreesign,self.currenthmdtysens1 )
			
		
		DB=ReadDatabase.GetRainfall(self.variables,days=1)
		rainfall=DB.periodrainfall
		if rainfall > 0:
			self.tweettext=u"%sToday's rainfall = %.2fmm" % (self.tweettext,rainfall)
			
	def SendTweet(self,tweetvariables):	
		#print tweetvariables
		ConsumerKey=tweetvariables['ConsumerKey']
		ConsumerSecret=tweetvariables['ConsumerSecret']
		AccessKey=tweetvariables['AccessKey']
		AccessSecret=tweetvariables['AccessSecret']
		update=tweetvariables['update']
		
		longitude=tweetvariables['long']
		latitude=tweetvariables['lat']

		auth=tweepy.OAuthHandler(ConsumerKey,ConsumerSecret)
		auth.set_access_token(AccessKey,AccessSecret)
		api=tweepy.API(auth)
		
		twitterreturncode=api.update_status(status=update,lat=latitude,long=longitude)

		